<?php

namespace App\Http\Controllers\Api\Main;

use App\Http\Controllers\Api\User\ReBateController;
use App\Http\Models\User\UserBaseModel;
use App\Models\Cart;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\DB;
use App\Models\distribution;
class OrderController extends ApiController
{

    #获取用户订单 6:全部订单 0，未确认；1，已确认；2，已取消；3，无效；4，退货；
    public function userOrder(Request $request,Order $orderModel)
    {
    	$user_id = $request->user_id ?intval($request->user_id):0;
    	if(!$user_id){
    		return self::response(null,self::ERROR_CODE,'请填写用户id');
    	}

    	$type = $request->status ?? -1;
    	$type = intval($type);

        $result = $orderModel -> api_order_list(['orders.user_id'=>$user_id],$type);

    	if(!$result){
    		return self::response([],self::ERROR_CODE,'暂无订单');
    	}

    	return self::response($result,self::SUC_CODE);
    }


    #查询订单详情
    public function orderDetail(Request $request,Order $orderModel)
    {
    	$order_id = intval($request->order_id);
    	if(!$order_id){
    		return self::response(null,self::ERROR_CODE,'请填写订单id');
    	}

        $result = $orderModel -> api_order_list(['orders.id'=>$order_id]);
    	if(!empty($result)){
            $result = $result[0];
        }
    	return self::response($result,self::SUC_CODE);
    }

    #取消订单接口
    public function cancel(Request $request,Order $orderModel)
    {
        $validator = \Validator::make($request->all(),[
            'user_id'   => 'required | integer',
            'order_id'  => 'required | integer',
        ]);

        if($validator -> fails()){
            return self::response(null,self::ERROR_CODE,$validator);
        }

        if($orderModel -> api_cancel_order($request)){
            return self::response(null,self::SUC_CODE,'取消订单成功');
        }

        return self::response(null,self::ERROR_CODE,Order::$error);
    }

    #申请退款接口
    public function apply_refund(Request $request,Order $orderModel)
    {
        $validator = \Validator::make($request->all(),[
            'user_id'   => 'required | integer',
            'order_id'  => 'required | integer',
            'refund_reason' => 'required',
        ]);

        if($validator -> fails()){
            return self::response(null,self::ERROR_CODE,$validator);
        }

        if($orderModel -> api_apply_refund($request->all())){
            return self::response(null,self::SUC_CODE,'申请退款成功,请等待处理');
        }

        return self::response(null,self::ERROR_CODE,Order::$error);
    }

    #确认收货接口
    public function confirm_ship(Request $request,Order $orderModel)
    {
        $validator = \Validator::make($request->all(),[
            'user_id'   => 'required | integer',
            'order_id'  => 'required | integer',
        ]);

        if($validator -> fails()){
            return self::response(null,self::ERROR_CODE,$validator);
        }

        if($orderModel -> api_confirm_ship($request->all())){
            $order = Order::find($request->input('order_id'));
            distribution::where('order_sn',$order->order_sn)->update(['status'=>1]);
            return self::response(null,self::SUC_CODE,'确认收货成功');
        }

        return self::response(null,self::ERROR_CODE,Order::$error);
    }

    #申请退货接口
    public function apply_shipback(Request $request,Order $orderModel){
        $validator = \Validator::make($request->all(),[
            'user_id'   => 'required | integer',
            'order_id'  => 'required | integer',
            'reason'    => 'required',
        ]);

        if($validator -> fails()){
            return self::response(null,self::ERROR_CODE,$validator);
        }

        if($orderModel -> api_apply_shipback($request->all())){
            return self::response(null,self::SUC_CODE,'申请退货成功');
        }

        return self::response(null,self::ERROR_CODE,Order::$error);
    }

    public function balancePayment(Request $request)
    {
        $input = $request->all();
        if (empty($input['order_sn'])){
            return self::response(null,self::ERROR_CODE,'订单错误');
        }
        if (empty($input['uid'])){
            return self::response(null,self::ERROR_CODE,'尚未登录');
        }

        $order     = Order::where('order_sn',$input['order_sn'])->where('pay_status',0)->first();
        if (empty($order)){
            return self::response(null,self::ERROR_CODE,'订单不存在');
        }else{
            $order = $order->toArray();
        }

        $user      = UserBaseModel::getUser($input['uid']);
        $flag      = bccomp($order['money_paid'],$user['user_coin'],2);
        if($flag>0){
            return self::response(null,self::ERROR_CODE,'余额不足');
        }
        #减去订单金额
        $flag       = UserBaseModel::decreaseCoin($user['id'],$order['money_paid']);
        if ($flag>0){
            Order::where('order_sn',$input['order_sn'])->update(['pay_status'=>2]);
            return self::response(null,self::SUC_CODE,'支付成功');
        }else{
            return self::response(null,self::ERROR_CODE,'支付失败');
        }
    }

    #订单生成(优化方法改用事务并且优化逻辑，已替换原来的订单生成方法toOrder)
    public function testorder(Request $request,User $userModel,Order $orderModel)
    {
        $validator = \Validator::make($request->all(),[
            'consignee' => 'required',
            'country'   => 'required',
            'mac'       => 'required',
            'province'  => 'required',
            'district'  => 'required',
            'address'   => 'required',
            'mobile'    => 'required',
            'pay_fee'   => 'required',
            'money_paid'=> 'required',
            'goods'     => 'required | Array',
            'goods.goods_id'   => 'required',
            'goods.box_id'   => 'required'
        ]);

        #如果是微信支付，则查看是否绑定了open_id
//        if(isset($request->pay_id) && $request->pay_id == 0){
//            if(!$userModel->is_bind_openId($request->input('user_id'))){
//                return self::response(null,self::UN_BIND_OPENID,'未绑定open_id');
//            }
//        }

        if($validator->fails()){
            return self::response(null,self::ERROR_CODE,$validator);
        }

        if(!$order_sn = $orderModel->api_make_order($request)){
            return self::response(null,self::ERROR_CODE,Order::$error);
        }

        return self::response(['order_sn'=>$order_sn],self::SUC_CODE,'生成订单成功');
    }


    public function getExpressUrl($express_encode,$express_no,$callbackurl)
    {
       $url = " https://m.kuaidi1000.com/index_all.html?type={$express_encode}&postid={$express_no}&callbackurl={$callbackurl}";
       return $url;
    }

    /**个人中心各个状态订单的上标小数字数量
     * @param Request $request
     * @param Order $orderModel
     * @return mixed
     */
    public function order_num(Request $request,Order $orderModel)
    {
        $validator = \Validator::make($request->all(),[
            'user_id'   => 'required | integer',
        ]);

        if($validator->fails()){
            return self::response(null,self::ERROR_CODE,$validator);
        }

        return self::response($orderModel->api_order_statistic(['orders.user_id'=>$request->input('user_id')]));
    }

    #酒店管理员查看自己所在酒店的订单列表
    public function hotel_owner_order(Request $request,Order $order)
    {
        $validator = \Validator::make($request->all(),[
            'hotel_open_id'   => 'required',
        ]);

        if($validator->fails()){
            return self::response(null,self::ERROR_CODE,$validator);
        }

        return self::response($order->api_hotel_order_list(['open_id'=>$request->input('hotel_open_id')]));
    }




}
